//
//  LYStatusViewModel.swift
//  微博
//
//  Created by liuerying on 16/5/25.
//  Copyright © 2016年 liuerying. All rights reserved.
//  处理cell的显示的模型数据

import UIKit

class LYStatusViewModel: NSObject {
    
    //静态的正则表达式对象 表情
    static let emotcionRegex = try! NSRegularExpression(pattern: "\\[.*?\\]", options: [])
    //话题的正则表达式对象 #内容#
    static let topicRegex = try! NSRegularExpression(pattern: "#.*?#", options: [])
    
    //@某人的正字表达式 @林心如
    static let atSomeOneRegex = try! NSRegularExpression(pattern: "@\\w+", options: [])
    
    //url的正则表达式对象
    static let urlRegex = try! NSRegularExpression(pattern: "(http[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?", options: [])
    
    

    var status : LYStatuses?
    
    //头像
    var headViewURL:NSURL?
    //时间
    var time: String?{
    
        //实时跟新时间
        return NSDate.sinaDate(status?.created_at ?? "")?.fullDescription()
    }
    
    //微博来源
    var sourceText:String?
    
    //用户认证
    var verifiedView:UIImage?
    
    var mbrankView : UIImage?
    
    //转发
    var repostsText:String?
    
    //评论
    var commentsText: String?
    
    //点赞
    var  attitudesText: String?
    
    //原创微博的属性字符串
    var originalAttrbuiteString : NSAttributedString?
    //转发微博的正文的
    
    var reweetedAttrbuiteString: NSAttributedString?
    
 
    
    init(status: LYStatuses) {
        super.init()

        self.status = status
        
        headViewURL = NSURL(string: status.user?.profile_image_url ?? "")
        
        //认证用户
        dealMverifiedView()
        
        //计算用户等级
        dealxmbrankView()
        
        dealSoureText()
        
        
        commentsText = dealToolBarText(status.comments_count, defaultText: "评论")
        
        repostsText = dealToolBarText(status.reposts_count, defaultText: "转发")
        
        attitudesText = dealToolBarText(status.attitudes_count, defaultText: "赞")
       
        //微博付文本
        
        originalAttrbuiteString = dealWeiboText(status.text ?? "")
        
        reweetedAttrbuiteString = dealWeiboText(status.retweeted_status?.text ?? "")
    }
}


extension LYStatusViewModel{
    
    //处理微博文博  转换成属性文本
    func dealWeiboText(sourceText:String)-> NSAttributedString{
    
        //使用正则表达式 来查找 表情字符串
        //例如 [奥特曼][拜拜]
        
        let results = LYStatusViewModel.emotcionRegex.matchesInString(sourceText, options: [], range: NSRange(location: 0, length: sourceText.characters.count))
        
        let strM = NSMutableAttributedString(string: sourceText)
        //遍历结果集合
        //获取单个表情字符串
        for result in results.reverse(){
            //通过表情字符串在分组数组中查找 表情字符串对应的 '表情模型"'
            let range = result.rangeAtIndex(0)
            
            let emoticonStr = (sourceText as NSString).substringWithRange(range)
            
            if let em = findEmoticonWithChs(emoticonStr){
            
                let iamge = UIImage(contentsOfFile: em.imagePath ?? "")

                //获取字体对应的行高
                let font = UIFont.systemFontOfSize(orginalContentLabelFontSize)
                let fontWidth = font.lineHeight
                let imageText =  NSMutableAttributedString.yy_attachmentStringWithContent(iamge, contentMode: .ScaleToFill, attachmentSize: CGSize(width:fontWidth ,height:fontWidth), alignToFont: font, alignment: .Center)
                
                strM.replaceCharactersInRange(range, withAttributedString: imageText)

            }
            
         
        }
        
        
        //在给特殊的文本添加高亮颜色前先设置基本颜色
        strM.addAttributes([NSForegroundColorAttributeName : UIColor.darkGrayColor()], range: NSRange(location: 0, length: strM.length))
        //设置文字的大小
        strM.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(orginalContentLabelFontSize)], range:  NSRange(location: 0, length: strM.length))
        
        //查找字符串中的话题的字符串,添加颜色
        //addTopicHighlited(strM)
        addHighlighted(strM, regex: LYStatusViewModel.topicRegex)
        //给@某人添加高亮
        addHighlighted(strM, regex: LYStatusViewModel.atSomeOneRegex)
        //url的高亮显示
        addHighlighted(strM, regex: LYStatusViewModel.urlRegex)
        return strM

        
    }
    
    //所有的特殊文本
    private func addHighlighted(str: NSMutableAttributedString,regex: NSRegularExpression) {
        //获取属性字符串的对应的字符串
        let topicStr = str.string
        let results =  regex.matchesInString(topicStr, options: [], range: NSRange(location: 0, length: topicStr.characters.count))
        //遍历结果
        for result in results {
            
            let range = result.rangeAtIndex(0)
            //取出话题子串
            let border = YYTextBorder(fillColor: UIColor.darkGrayColor(), cornerRadius: 3)
            
            //实例化高亮对象
            let highlithed = YYTextHighlight()
            highlithed.setColor(UIColor.redColor())
            highlithed.setBackgroundBorder(border)
            //把"高亮"属性设置到某个文本范围
            str.yy_setTextHighlight(highlithed, range: range)
            
            
            //let subStr = (topicStr as NSString).substringWithRange(range)
            //给特殊的字符串添加高亮
            str.addAttributes([NSForegroundColorAttributeName : UIColor.blueColor()], range: range)
            //print(subStr)
        }
    }

    //根据表情字符串查找对应的模型对象
    private func findEmoticonWithChs(chs: String)->LYEmoticon?{
        
        //获取分组的表情
        for p in LYEmoticonManager.sharedEmoticonTools.packages {
            //获取二维数组中的每一个小数组
            for emoticons in p.sectionEmoticon {
                //在数组中根据表情字符串查找对应的模型对象
                let array = emoticons.filter({ (em) -> Bool in
                    //返回查找的条件  就是目标对象
                    return chs == em.chs
                })
                print(array)
                if array.count > 0 {
                    //根据chs 查询到了模型对象
                    return array.first
                }
            }
        }
        
        return nil
        
        
    }
    
    //换算评论栏的内容
    func dealToolBarText(count: Int ,defaultText: String) -> String {
    
        if count <= 0 {
            return defaultText
        }
        //大于一万
        if count >= 10000 {
            return "\(Double(count / 1000) / 10)万"
        }
        return "\(count)"
    }
    
    

    //处理微博来源的方法
    private func dealSoureText(){
    
        //<a href="http://weibo.com/" rel="nofollow">微博 weibo.com</a>
        
        let startFlag = "\">"
        let endFlag = "</a>"
        //获取模型字符串
        let str = status?.source ?? ""
        
        let startRange = str.rangeOfString(startFlag)
        let EndRange = str.rangeOfString(endFlag)
        
        if let start = startRange, end = EndRange {
        
            let rang = start.endIndex..<end.startIndex
            
            sourceText = str.substringWithRange(rang)
            
        }
    }
    
    //认证用户
   private func dealMverifiedView(){
    
    let type = status?.user?.verified ?? 0
    
    if type == 1 {
        
        verifiedView = UIImage(named: "avatar_vip")
 
    }
   

    }
    //用户等级计算
   private func dealxmbrankView(){
    
        if status?.user?.mbrank > 0 && status?.user?.mbrank < 7{
            
            mbrankView = UIImage(named: "common_icon_membership_level\(status?.user?.mbrank ?? 0)")

        }
 
    }

}
